# == Schema Information
# Schema version: 6
#
# Table name: comments
#
#  id               :integer(11)   not null, primary key
#  title            :string(50)    default("")
#  comment          :text          
#  created_at       :datetime      not null
#  commentable_id   :integer(11)   default(0), not null
#  commentable_type :string(15)    default(""), not null
#  user_id          :integer(11)   default(0), not null
#

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic=>true
  belongs_to :user
  validates_presence_of :title, :comment, :commentable_type, :commentable_id, :allow_nil=>false
  validates_numericality_of :commentable_id, :user_id, :allow_nil=>false
  
  def validate
    unless self.user(true)
      self.errors.add(:user_id, "is not a valid user id")
    end

    if self.commentable_id == 0 or self.commentable_id.nil?
      self.errors.add(:commentable_id, "must be positive")
    end
    
    unless self.commentable_type.blank? or self.commentable_type.nil?
      begin
       self.commentable_type.constantize
       if self.commentable_type.constantize.find(self.commentable_id)
         unless self.commentable_type.constantize.ancestors.include?(ActiveRecord::Base)
          self.errors.add(:commentable_type, "is not a subclass of activerecord")
         end
       end
      rescue NameError
        self.errors.add(:commentable_type, "does not contain a valid class name")
      rescue ActiveRecord::RecordNotFound
        self.errors.add(:commentable_id, "is not a valid #{self.commentable_type} object")
      end
    end
  end
end
